﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SQLite;
using SingletonPattern.utils;

namespace SingletonPattern.Model
{
    public class UserModel: BaseModel, IUserModel
    {
        public void getUser()
        {
            DataTable dt = new DataTable();
            try
            {
                this.conn.Open();
                SQLiteHelper hp = new SQLiteHelper(this.conn.CreateCommand());
                string sql = "select * from user"
                            + " where id = 1";
                dt = hp.Select(sql);
            }
            catch (SQLiteException ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.Message);
            }
            finally
            {
                this.conn.Close();
            }
            foreach (DataRow row in dt.Rows)
            {
                foreach (DataColumn  col in dt.Columns)
                {
                    CurrentSetting.Instance[col.ColumnName] = row[col.ColumnName].ToString();
                }
            }
        }

        public void updateUser()
        {
            try
            {
                this.conn.Open();
                SQLiteHelper hp = new SQLiteHelper(this.conn.CreateCommand());
                StringBuilder sqlUpdate = new StringBuilder();
                StringBuilder sqlSet = new StringBuilder();
                StringBuilder sqlWhere = new StringBuilder();
                foreach (string key in CurrentSetting.Instance.Keys)
                {
                    if (sqlSet.Length != 0)
                    {
                        if (sqlUpdate.Length != 0)
                        {
                            sqlSet.Append(", ");
                        }
                        else
                            sqlUpdate.Append("update user set");
                        sqlSet.Append(key);
                        sqlSet.Append("=@");
                        sqlSet.Append(key);
                    }
                    else
                    {
                        sqlWhere.Append(" where ");
                        sqlWhere.Append(key);
                        sqlWhere.Append("=@");
                        sqlWhere.Append(key);
                        sqlSet.Append(" ");
                    }
                }
                string sql = sqlUpdate.ToString() + sqlSet.ToString() + sqlWhere.ToString();
                hp.Execute(sql, CurrentSetting.Instance);
            }
            catch (SQLiteException ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.Message);
            }
            finally
            {
                this.conn.Close();
            }
        }
    }
}
